package com.domor.xxx.framework.shiro.service;

import com.domor.xxx.common.constant.ShiroConstants;
import com.domor.xxx.common.exception.UserException;
import com.domor.xxx.common.utils.StringUtils;
import com.domor.xxx.system.domain.SysUser;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 登录密码验证相关方法
 *
 * @author liyuyang
 */
@Component
public class SysPasswordService {

    @Autowired
    private CacheManager cacheManager;

    private Cache<String, AtomicInteger> loginRecordCache;

    @Value(value = "${user.password.maxRetryCount}")
    private String maxRetryCount;

    @PostConstruct
    public void init() {
        loginRecordCache = cacheManager.getCache(ShiroConstants.LOGINRECORDCACHE);
    }

    /**
     * 登录密码验证
     */
    public void validate(SysUser user, String password) {
        String loginName = user.getLoginName();

        AtomicInteger retryCount = loginRecordCache.get(loginName);

        if (retryCount == null) {
            retryCount = new AtomicInteger(0);
            loginRecordCache.put(loginName, retryCount);
        }
        if (retryCount.incrementAndGet() > Integer.valueOf(maxRetryCount).intValue()) {
            String msg = StringUtils.format(UserException.RETRY_LIMIT_EXCEED, maxRetryCount);
            throw new UserException(msg);
        }

        if (!matches(user, password)) {
            String msg = StringUtils.format(UserException.RETRY_LIMIT_COUNT, retryCount);
            loginRecordCache.put(loginName, retryCount);
            throw new UserException(msg);
        } else {
            clearLoginRecordCache(loginName);
        }
    }

    /**
     * 校验密码是否正确
     */
    public boolean matches(SysUser user, String newPassword) {
        String nPwd = encryptPassword(user.getLoginName(), newPassword, user.getSalt());
        return user.getPassword().equals(nPwd);
    }

    /**
     * 清除登录失败日志缓存
     */
    public void clearLoginRecordCache(String username) {
        loginRecordCache.remove(username);
    }

    /**
     * 密码加密
     */
    public String encryptPassword(String username, String password, String salt) {
        return new Md5Hash(username + password + salt).toHex();
    }

    /**
     * 解除帐记锁定
     */
    public void unlock(String loginName) {
        loginRecordCache.remove(loginName);
    }

}
